#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <string>
#include <pthread.h>
#include <cstring>
#include <cstdio>
#include <unistd.h>
#include <functional>

namespace ThreadModlue
{
    // bug
    static uint32_t number = 1;
    class Thread
    {
        using func_t = std::function<void()>;

    private:
        void EnableDetach()
        {
            _isdetach = true;
        }
        void EnableRunning()
        {
            _isrunning = true;
        }
        static void *Routine(void *args) // 属于类内成员函数，函数参数有this，static可以解决
        {
            Thread *self = static_cast<Thread *>(args);
            self->EnableRunning();
            if (self->_isdetach)
                self->Detach();
            self->_func(); // 回调处理，static没有this指针
            return nullptr;
        }

    public:
        Thread(func_t func) : _tid(0),
                              _isdetach(false),
                              _isrunning(false),
                              _func(func)
        {
            _name = "thread-" + std::to_string(number++);
        }
        void Detach()
        {
            std::cout << "你的线程已经被分离" << '\n';
            if (_isdetach)
                return;
            if (_isrunning)
                pthread_detach(_tid);
            EnableDetach();
        }

        bool Start()
        {
            if (_isrunning)
                return false;
            int n = pthread_create(&_tid, nullptr, Routine, this);
            if (n > 0)
            {
                std::cerr << "create thread error" << strerror(n) << '\n';
                return false;
            }
            else
            {
                std::cout << "create thread true" << '\n';
                return true;
            }
            EnableRunning();
            if (_isdetach)
                pthread_detach(_tid);
        }
        void stop()
        {
            if (_isrunning)
            {
                int n = pthread_cancel(_tid);
                if (n != 0)
                {
                    std::cerr << "create thread error: " << strerror(n) << '\n';
                }
                else
                {
                    _isrunning = false;
                    std::cout << _name << " stop" << '\n';
                }
            }
        }
        void Join()
        {
            if (_isdetach)
            {
                std::cout << "你的线程已经分离了，不用join" << '\n';
                return;
            }
            int n = pthread_join(_tid, &res);
            if (n != 0)
            {
                std::cerr << "create thread error: " << strerror(n) << '\n';
            }
        }
        ~Thread() {}

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
    };
}

#endif